package cn.kgc.ssm.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.ssm.web.entity.Member;
import cn.kgc.ssm.web.entity.Message;
import cn.kgc.ssm.web.mapper.MessageMapper;
import cn.kgc.ssm.web.response.ResponseResult;
import cn.kgc.ssm.web.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 课工场
 * @date 2024/7/31
 * @description
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Override
    public ResponseResult messagePage(Integer page, Integer limit, String memberName) {

        // 1.开启分页
        PageHelper.startPage(page,limit);
        List<Message> messages =  messageMapper.selectList(memberName);
        PageInfo<Message> messagePageInfo = new PageInfo<>(messages);
        long total = messagePageInfo.getTotal();
        return ResponseResult.success().data(messages).count(total);

    }

    @Override
    public ResponseResult editMessage(Integer id) {

        messageMapper.editMessageStatus(id);
        return ResponseResult.success();
    }


    @Transactional
    @Override
    public ResponseResult deleteMessage(Integer[] ids) {

        List<Message> messages =   messageMapper.selectMessages(ids);
        List<Message> collect = messages
                .stream()
                .filter(message -> message.getStatus() == 0)
                .collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(collect)){
            return ResponseResult.fail().message("留言未回访,不能删除");
        }

        messageMapper.deleteMessages(ids);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult publishMessage(String content, HttpSession session) {

        Member member = (Member) session.getAttribute("member");
        String memberName = member.getMemberName();
        String tel = member.getTel();

        Message message = new Message();
        message.setContent(content);
        message.setMemberName(memberName);
        message.setTel(tel);

        messageMapper.addMessage(message);

        return ResponseResult.success();
    }
}
